<script type="text/javascript">
const SENTINEL = -999;


Number.prototype.toFixed=function(x) {
// Round a float
   var temp=this;
   temp=Math.round(temp*Math.pow(10,x))/Math.pow(10,x);
   return temp;
} 

function toCelsius(F) {
// Convert from Fahrenheit to Celsius
  return 100/(212-32) * (F - 32 );
}

function updateReading(roomId, zoneId, reading, setpoint, timestamp, mode, scale) {
  nodeIdPrefix = "#room-"+roomId+"-zone-"+zoneId+"-";
  if ((reading != SENTINEL) && (mode == "cool")) {
    if (reading > setpoint) {  // too hot
      $(nodeIdPrefix + "reading").addClass("cool-above-setpoint");
    } else {
      $(nodeIdPrefix + "reading").removeClass("cool-below-setpoint");
    }
  }
  if ((reading != SENTINEL) && (mode == "heat")) {
    if (reading < setpoint) {  // too cold
      $(nodeIdPrefix + "reading").addClass("heat-below-setpoint");
    } else {
      $(nodeIdPrefix + "reading").removeClass("heat-above-setpoint");
    }
  }
  
  if ((reading != SENTINEL) && (scale == "C")) { 
    reading  = toCelsius(reading);
  }
  if (reading != SENTINEL) {
    $(nodeIdPrefix + "reading").html(reading.toFixed(1)+" &deg;"+scale);
    $(nodeIdPrefix + "reading").attr('title', function() { return timestamp });
    //$(nodeIdPrefix + "timestamp").html(timestamp);
  } else {
    $(nodeIdPrefix + "reading").html("x");
    $(nodeIdPrefix + "reading").attr('title', function() { return "N/a" });
    //$(nodeIdPrefix + "timestamp").html("N/a");
  }
}



function updateStatus(roomId, zoneId, vent, mode, timestamp) {
  nodeIdPrefix = "#status-"+roomId+"-zone-"+zoneId;
  if (vent.length != 0) {
    $(nodeIdPrefix + "-vent").html(vent);
    $(nodeIdPrefix + "-mode").html(mode);
    $(nodeIdPrefix).attr('title', function() { return timestamp });
  } else {
    $(nodeIdPrefix + "-vent").html("N/a");
    $(nodeIdPrefix + "-mode").html("N/a");
    $(nodeIdPrefix).attr('title', function() { return "N/a" });
  }
}




function getReadings(mode, scale) {
// Get latest temperature readings  
  var times=0; // # of times to repeat, 0 = unbounded  

  // setpoints
  <? foreach ($this->rooms as $room): ?>
    setpoint  = (scale == "C") ?  toCelsius(<?= $room['setpoint'] ?>) : <?= $room['setpoint'] ?>;
    $("a").filter("#setpoint-<?=$room['room_id']?>").html(setpoint.toFixed(1) + " &deg " + scale);
  <? endforeach ?>

  //-----------------------
  // Initial update 
  // we don't want to wait 5s for first update
  // initial temperature readings
  <? foreach ($this->rooms as $room): ?>
    $.post("reading", {id: <?= $room['zone_ids'][0] ?>}, function(xml) {
        setpoint  = <?= $room['setpoint'] ?>;
        reading   = (($("reading", xml).text()).length > 0) ?  ($("reading", xml).text())/1 : SENTINEL; //convert to int
        timestamp = $("timestamp", xml).text();
        updateReading(<?=$room['room_id']?>, <?= $room['zone_ids'][0] ?>, reading,
                      setpoint, timestamp, mode, scale);
    });

    $.post("status", {id: <?= $room['zone_ids'][0] ?>}, function(xml) {
        vent = $("vent", xml).text();
        status_mode = $("mode", xml).text(); 
        timestamp = $("timestamp", xml).text();
        updateStatus(<?=$room['room_id']?>, <?= $room['zone_ids'][0] ?>, vent, status_mode, timestamp);
    });
  <? endforeach ?>
        
        
  //-----------------------
  // Periodic updates      
  // refresh every 5s
  $(document).everyTime(5000, function() { //5s
    // send request for temp
<? foreach ($this->rooms as $room): ?>
    $.post("reading", {id: <?= $room['zone_ids'][0] ?>}, function(xml) {
      setpoint  = <?= $room['setpoint'] ?>;
      reading   = (($("reading", xml).text()).length > 0) ?  ($("reading", xml).text())/1 : SENTINEL; //convert to int
      timestamp = $("timestamp", xml).text();
      
      updateReading(<?=$room['room_id']?>, <?= $room['zone_ids'][0] ?>, reading,
                    setpoint, timestamp, mode, scale);
    });
    // status
    $.post("status", {id: <?= $room['zone_ids'][0] ?>}, function(xml) {
        vent = $("vent", xml).text();
        status_mode = $("mode", xml).text(); 
        timestamp = $("timestamp", xml).text();
        updateStatus(<?=$room['room_id']?>, <?= $room['zone_ids'][0] ?>, vent, status_mode, timestamp);
    });

<? endforeach ?>    
  }, times);  
}

jQuery(document).ready(function() {
	// Add new room button
	$("button").filter(".addme").click(function(){
    //alert("You are now leaving the site.");
    window.location.replace('<?= $this->url(array('controller'=>'room', 'action'=>'add'), 'default', true) ?>');
    return false;
  });
  

  $.post("setting", {}, function(xml) {
    mode   = ($("mode", xml).attr("value"));
    scale = ($("scale", xml).attr("value"));
    getReadings.call(this, mode, scale);
  });

});
</script>

<!-- Loop through the entries that were provided to us by the controller -->
<table width="100%" style="padding-top:0; margin-top:0;">
<tr>
<?php $ncols=2; ?>
<?php $i=1; ?>
<? foreach ($this->rooms as $room): ?>
<!-- TBD: multiple temperature reading per room -->
<td>
  <div class="sidebox">
  	<div class="boxhead"><h2><?= $this->escape($room['name']) ?></h2></div>
  	<div class="boxbody">
  	  <div class="r-edit"><a href="<?= $this->url(
            array('controller'=>'room','action'=>'edit','room_id'=>$room['room_id']), 
            'default', true) ?>" title="Change name, setpoint, sensors">Edit</a></div>
  		<div class="temp"><span id="room-<?=$room['room_id']?>-zone-<?= $room['zone_ids'][0] ?>-reading" title=""><img src="../gfx/wait24trans.gif" /></span></div>
  		<div class="udate">
        Setpoint:
        <a id="setpoint-<?= $room['room_id'] ?>" href="<?= $this->url(
              array('controller'=>'setpoint','action'=>'edit','room_id'=>$room['room_id']), 
              'default', true) ?>" title="Change setpoint temperature"></a><br />
        Status:
  		  <span id="status-<?=$room['room_id']?>-zone-<?= $room['zone_ids'][0] ?>" class="uline" title="">
  		    <span id="status-<?=$room['room_id']?>-zone-<?= $room['zone_ids'][0] ?>-vent"></span> vent, 
  		    <span id="status-<?=$room['room_id']?>-zone-<?= $room['zone_ids'][0] ?>-mode"></span>
  		  </span><br />  		
<!--  		  <small> Updated:
  		  <span id="room-<?=$room['room_id']?>-zone-<?= $room['zone_ids'][0] ?>-timestamp">-</span>	
  		  </small>
-->  		  
      </div>
  	</div>
  </div>
<?php if (($i%$ncols) == 0): ?>
  </tr><tr>
<?php endif?>
</td>
<?php $i++; ?>
<? endforeach ?>
<!-- Add Room -->
<td>
  <div class="sidebox">
  	<div class="boxhead"><h2>Add Room</h2></div>
  	<div class="boxbody">
  		<div class="temp">
  		  <form style="margin:0 5px 20px 5px; padding:0;"><button class="addme">Add Room</button></form>
  		  </div>
  		<div class="udate">
      	</div>
      </div>  
</td>

<!-- Add missing table cells -->
<?php $k=(($i%$ncols)); ?>
<? for($j=0; $j < $k; $j++): ?>
<td>&nbsp;</td>
<? endfor ?>
</tr>
</table>
<?php //phpinfo();
